package com.farm.controller;

import com.farm.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("/common")
@Slf4j
@RestController
public class ImageController {
    @Value("${image.basePath}")
    private String basePath;

    /**
     * 批量图片的上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){

            log.info("开始接收文件" + file.toString());

            // 获取文件原始名字
            String originalFilename = file.getOriginalFilename();
            // 截取文件后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 利用uuid生成新的文件名
            String filename = UUID.randomUUID().toString() + suffix;
            // 创建文件目录
            File dir = new File(basePath);
            if (!dir.exists()){
                // 文件不存在开始创建
                dir.mkdir();
            }
            // 将文件转存在本地文件中
            try {
                file.transferTo(new File(basePath + filename));
            } catch (IOException e) {
                e.printStackTrace();
            }


        return R.success(filename);
    }

    /**
     * 文件的下载
     * @param filename
     * @param response
     */
    @GetMapping("/download")
    public void download(String filename, HttpServletResponse response){
            try {
                // 输入流读取文件中的内容
                File file = new File(basePath + filename);
                if(file.exists()){
                    log.info("文件的下载：" + filename);
                    FileInputStream fileInputStream = new FileInputStream(file);
                    // 定义输入流，通过输入流写回给浏览器
                    ServletOutputStream outputStream = response.getOutputStream();

                    // 返回的数据格式
                    response.setContentType("image/jpeg");
                    int len = 0;
                    byte[] bytes = new byte[4096];
                    while((len = fileInputStream.read(bytes)) != -1){
                        outputStream.write(bytes,0,len);
                        outputStream.flush();
                    }
                    outputStream.close();
                    fileInputStream.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }


}
